<?php
namespace App\Repository;

use App\Model\MallGoods;

class MallGoodsRepository extends \HyperfStore\Repository
{
    // 放入模型
    public function build()
    {
        return new MallGoods;
    }
    
    // 创建
    public function create($data, MallShopRepository $shop = null)
    {
        // 附加商家
        if($shop)
        {
            $this->model->shop()->associate($shop->model());
        }
        
        return $this->exception(function() use($data) {
            return $this->save($data);
        });
    }
    
    // 审核商品
    public function setStatus($status, $sort, $money)
    {
        $this->model->status = (int) $status;
        $this->model->sort = (int) $sort;
        $this->model->money_settle = (float) $money;
        
        return $this->model()->save();
    }
    
    // 状态
    public function statusOk()
    {
        return $this->model->status == MallGoods::STATUS_OK;
    }
    
    // 限制时间
    public function isDay()
    {
        if($this->model->day)
        {
            return time() - ($this->model->day * 60 * 60 * 24);
        }
    }
    
    // 限制数量
    public function isDayCount($count)
    {
        return $this->model->day_count < $count;
    }
    
    // 删除商品
    public function delete()
    {
        return $this->model->delete();
    }
    
    // 验证库存
    public function hasCount($count)
    {
        if($count < 1)
        {
            return;
        }
        
        return $this->model->count >= $count;
    }
    
    // 删除库存
    public function delCount($count)
    {
        if($this->hasCount($count))
        {
            return $this->model->decrement('count', $count);
        }
    }
    
    // 放回库存
    public function addCount($count)
    {
        return $this->model->increment('count', $count);
    }
    
    // 换算现金金额
    public function moneyPay($count = 1)
    {
        return bcmul($this->model->money_pay, $count, 2);
    }
    
    // 换算购物积分
    public function moneyShop($count = 1)
    {
        return bcmul($this->model->money_shop, $count, 2);
    }
    
    // 换算兑换积分
    public function moneyPoint($count = 1)
    {
        return bcmul($this->model->money_point, $count, 2);
    }
    
    // 换算运费
    public function moneyExpress($count = 1)
    {
        $money = $this->model->money_express;
        
        // 是否按商品数量叠加
        if($this->model->express_append)
        {
            $money = bcmul($money, $count, 2);
        }
        
        return $money;
    }
    
    // 结算金额
    public function moneySettle($count = 1)
    {
        return bcmul($this->model->money_settle, $count, 2);
    }
}